package cn.hd01.weixin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.Customer;
import cn.hd01.service.CustomerService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.auth.AuthType;
import cn.hd01.web.util.WebHelper;
import cn.hd01.weixin.model.Result;

@Controller
@RequestMapping("/weixin/login")
@Auth(AuthType.WECHAT)
public class WXLogin {

	@Autowired
	private CustomerService customerService;

	@RequestMapping(path = "", method = RequestMethod.GET)
	public String toLogin() {
//		Customer customer = cusomterService.findByOauthId(WebHelper.currentWXOauth().getId());
//		if (customer != null && customer.getActivationStatus()) {
//			return "redirect:/weixin/customer";
//		}
		
		return "weixin/login";
	}

	@ResponseBody
	@RequestMapping(path = "", method = RequestMethod.POST)
	public Result submitLogin(String mobile, String password) {
		Customer customer = customerService.findByPhoneNo(mobile);
		if (customer == null) {
			return new Result(false, "用户不存在");
		}

		if (!password.equals(customer.getPassword())) {
			return new Result(false, "密码错误");
		}

		Customer old = customerService.findByOauthId(WebHelper.currentWXOauth().getId());
		if (old != null) {
			old.setOauthId(null);
			customerService.save(old);
		}
		
		customer.setOauthId(WebHelper.currentWXOauth().getId());
		customer.setHeadImage(WebHelper.currentWXOauth().getHeadimgurl());
		customerService.save(customer);
		return new Result();
	}
}
